from datetime import datetime
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

# 团队成员表
class TeamMember(db.Model):
    __tablename__ = 'team_members'
    id      = db.Column(db.Integer, primary_key=True)
    team_id = db.Column(db.Integer, db.ForeignKey('teams.teamID'), nullable=False)
    user_id = db.Column(db.Integer, nullable=False)  # 这里只存用户 id，不建 User 表

    def to_dict(self):
        return {"user_id": self.user_id}

# 团队项目表
class TeamProject(db.Model):
    __tablename__ = 'team_projects'
    id      = db.Column(db.Integer, primary_key=True)
    team_id = db.Column(db.Integer, db.ForeignKey('teams.teamID'), nullable=False)
    project_id = db.Column(db.Integer, nullable=False)  # 这里只存项目 id，不建 Project 表

    def to_dict(self):
        return {"project_id": self.project_id}

# 主表：团队
class Team(db.Model):
    __tablename__ = 'teams'

    # 主键
    teamID = db.Column(db.Integer, primary_key=True, autoincrement=True)

    # 普通字段
    teamName   = db.Column(db.String(128), nullable=False)
    teamLeader = db.Column(db.Integer, nullable=False)  # 创建者 user_id
    team_intro = db.Column(db.Text,
                           default="a team that develops agents")
    team_avatar = db.Column(db.String(512),
                            default="https://img95.699pic.com/photo/30544/5016.jpg_wh860.jpg")

    # 时间戳
    createdAt = db.Column(db.DateTime, default=datetime.utcnow)
    updatedAt = db.Column(db.DateTime,
                          default=datetime.utcnow,
                          onupdate=datetime.utcnow)

    # 一对多关系
    members  = db.relationship('TeamMember',
                               backref='team',
                               cascade='all, delete-orphan',
                               lazy=True)
    projects = db.relationship('TeamProject',
                               backref='team',
                               cascade='all, delete-orphan',
                               lazy=True)

    # 方便直接转成原来接口用的 dict
    def to_dict(self):
        return {
            "teamID": self.teamID,
            "teamName": self.teamName,
            "teamLeader": self.teamLeader,
            "team_intro": self.team_intro,
            "team_avatar": self.team_avatar,
            "createdAt": self.createdAt.isoformat(),
            "updatedAt": self.updatedAt.isoformat(),
            "members": [m.user_id for m in self.members],
            "projects": {str(p.project_id): {} for p in self.projects}
        }

    # 创建团队时快速初始化
    @classmethod
    def create(cls, name: str, leader: int):
        new_team = cls(
            teamName=name,
            teamLeader=leader
        )
        # 把创建者塞进成员表
        new_team.members.append(TeamMember(user_id=leader))
        return new_team